package com.hu.auth.common.exception;

import com.hu.auth.common.result.R;
import com.hu.auth.common.result.RCodeEnum;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;

@ControllerAdvice
public class GlobalExceptionHandler {

    // 算术异常处理
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public R error(ArithmeticException e) {
        e.printStackTrace();
        return R.fail().message("算术异常");
    }

    // 自定义异常处理
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public R error(CustomException e) {
        e.printStackTrace();
        return R.fail().code(e.getCode()).message(e.getMsg());
    }

    // 自定义验证异常
    @ExceptionHandler(value = {BindException.class, MethodArgumentNotValidException.class})
    @ResponseBody
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return R.fail().message(message);
    }

    // 请求方式错误异常
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public R handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return R.fail().code(RCodeEnum.ILLEGAL_REQUEST.getCode()).message(RCodeEnum.ILLEGAL_REQUEST.getMessage());
    }

    // sql错误异常
    @ExceptionHandler(SQLException.class)
    @ResponseBody
    public R handleSQLException(SQLException e) {
        return R.fail().code(RCodeEnum.SQL_ERROR.getCode()).message(RCodeEnum.SQL_ERROR.getMessage());
    }

    // 全局异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e) {
        e.printStackTrace();
        return R.fail().message("执行了全局异常处理");
    }

    // /**
    //  * spring security异常
    //  *
    //  * @param e
    //  * @return
    //  */
    // @ExceptionHandler(AccessDeniedException.class)
    // @ResponseBody
    // public R error(AccessDeniedException e) throws AccessDeniedException {
    //     return R.fail().code(RCodeEnum.PERMISSION.getCode()).message("没有当前功能操作权限");
    // }

}
